package com.tupu.service.impl.permission;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tupu.entity.permission.PermissionInfo;
import com.tupu.mapper.permission.PermissionListMapper;
import com.tupu.service.permission.PermissionListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionListServiceImpl extends ServiceImpl<PermissionListMapper, PermissionInfo> implements PermissionListService {

    @Autowired(required = false)
    private PermissionListMapper permissionListMapper;

    /**
     * 查询父节点和子节点，无限极分类
     *
     * @return
     */
    public List<PermissionInfo> findAll() {
        List<PermissionInfo> lists = permissionListMapper.selectList(null);
        //找到一级目录
        List<PermissionInfo> arrayList = new ArrayList<>();
        for (PermissionInfo per : lists) {
            if (per.getParentId() == 0) {
                arrayList.add(per);
            }
        }
        //子目录
        for (PermissionInfo per : arrayList) {
            per.setChildren(getChild(per.getPermissionId(), lists));
        }
        return arrayList;
    }

    /**
     * 递归查询子菜单
     *
     * @param permissionId
     * @param lists
     * @return
     */
    private List<PermissionInfo> getChild(Integer permissionId, List<PermissionInfo> lists) {
        //子级
        List<PermissionInfo> childList = new ArrayList<>();
        for (PermissionInfo per : lists) {
            //遍历所有节点 查询父级id
            if (per.getParentId().equals(permissionId)) {
                childList.add(per);
            }
        }
        //循环子级
        for (PermissionInfo per : childList) {
            per.setChildren(getChild(per.getPermissionId(), lists));
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
